package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    /**
     * 在请求到达控制器之前先经过拦截器的preHandle()方法，再这里做认证
     */
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        log.info("拦截器拦截校验,请求的ip地址：{}，请求地址：{}",
                request.getRemoteAddr(),request.getRequestURL());

        //1. 获取请求头：token
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            // 401 表示认证失败
            response.setStatus(401);
            // false 不放行，不执行控制器的方法
            return false;
        }

        //2. 根据token获取redis中的用户json字符串, 转换为User对象
        User user = userService.findUserByToken(token);
        if (user == null) {
            response.setStatus(401);
            return false;
        }

        //3. 把User对象绑定到当前线程上(这样就可以在service中通过ThreadLocal获取认证的用户对象)
        UserHolder.set(user);
        return true;
    }
}
